package com.wlbx.agent.ui.fragment.tab;

import android.Manifest;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.tools.ToastUtils;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseFragment;
import com.wlbx.agent.bean.AccountInfoBean;
import com.wlbx.agent.bean.IncomeBean;
import com.wlbx.agent.event.UpdateUserInfoEvent;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.ui.activity.LoginActivity;
import com.wlbx.agent.ui.activity.MessageActivity;
import com.wlbx.agent.ui.activity.PersonalActivity;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 我的
 */
public class MineFragment extends BaseFragment {

    @BindView(R.id.iv_setting)
    ImageView ivSetting;

    @BindView(R.id.iv_header)
    ImageView ivHeader;

    @BindView(R.id.iv_message)
    ImageView ivMessage;

    @BindView(R.id.ll_personal)
    LinearLayout llPersonal;

    @BindView(R.id.tv_user_name)
    TextView tvUserName;

    @BindView(R.id.tv_income)
    TextView tvIncome;

    @BindView(R.id.tv_total_count)
    TextView tvTotalCount;

    @BindView(R.id.tv_total_annual_prem)
    TextView tvTotalAnnualPrem;
    @BindView(R.id.ll_my_order)
    LinearLayout llMyOrder;

    @BindView(R.id.ll_my_claim)
    LinearLayout llMyClaim;

    @BindView(R.id.ll_customer)
    LinearLayout llCustomer;

    @BindView(R.id.rl_help_center)
    RelativeLayout rlHelpCenter;

    @BindView(R.id.ll_count)
    LinearLayout llCount;

    @BindView(R.id.rl_contact_us)
    RelativeLayout rlContactUs;

    @BindView(R.id.tv_msg_flag)
    TextView tvMsgFlag;

    private String name;
    private String workNo;
    private String loginPwdFlag;
    private String mobile;



    @Override
    protected int getInflateViewId() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initData() {
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        if(checkLogin()) {
            getIncomeInfo();
            getInfo();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
            fresh_message();
    }

    private void getIncomeInfo() {
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getIncomeInfo()
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i(response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg  = jsonObject.getString("msg");
                        if("1000".equals(rCode)) {
                            IncomeBean incomeBean=JSON.parseObject(response,IncomeBean.class);
                                tvIncome.setText(incomeBean.getData().getIncome()+"");
                                tvTotalCount.setText(incomeBean.getData().getTotalCount()+"");
                                tvTotalAnnualPrem.setText(incomeBean.getData().getTotalAnnualPrem()+"");
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i(t.getMessage());

                    }
                });
    }

    @Override
    public void initEvent() {
    }

    @OnClick({R.id.iv_setting,R.id.iv_header,R.id.ll_my_order,R.id.ll_my_claim,R.id.ll_customer,R.id.rl_help_center,R.id.iv_message,R.id.rl_join_us,R.id.ll_count,R.id.rl_contact_us})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_setting:
                IntentUtil.goSettingActivity(getActivity());
                break;
            case R.id.iv_header:
                IntentUtil.goPersonalActivity(getActivity());
                break;
            case R.id.ll_my_order:
                IntentUtil.goMyOrderActivity(getActivity());
                break;
            case R.id.ll_customer:
                IntentUtil.goCustomerListActivity(getActivity());
                break;
            case R.id.rl_help_center:
                IntentUtil.goHelpCenterActivity(getActivity());
                break;
            case R.id.rl_join_us:
                IntentUtil.goJoinWanliActivity(getActivity());
                break;
            case  R.id.iv_message:
                startActivity(new Intent(this.mActivity, MessageActivity.class));
                break;
            case R.id.ll_count:
                IntentUtil.goRevenueActivity(getActivity());
                break;
            case R.id.rl_contact_us:
                showPopupWindow();
                break;
            case R.id.ll_my_claim:
                IntentUtil.goMyClaimActivity(getActivity());
                break;
            default:
                break;
        }
    }

    public void getInfo() {
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getPersonalInfo()
                .enqueue(new RetrofitCallBack() {

                    @Override
                    public void onSuccess(String response) {
                        Logger.i("event---"+response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                        AccountInfoBean accountInfoBean=JSON.parseObject(response,AccountInfoBean.class);
                            tvUserName.setText(accountInfoBean.getData().getName());
                            Glide.with(getActivity()).load(accountInfoBean.getData().getImage()).into(ivHeader);
//                            SPUtil.putValue(Constant.USER_INFO,Constant.NAME,accountInfoBean.getData().getName());
//                            SPUtil.putValue(Constant.USER_INFO,Constant.IMAGE,accountInfoBean.getData().getImage());
//                            SPUtil.putValue(Constant.USER_INFO,Constant.WORK_NO,accountInfoBean.getData().getWorkNo());
                            getRegistrationId(accountInfoBean.getData().getMobile());
                            JPushInterface.setAlias(getActivity(),0,accountInfoBean.getData().getMobile());
                        }else if ("5000".equals(rCode)){
                            IntentUtil.goLoginActivity(getActivity());
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i(t.getMessage());

                    }
                });
    }
    private void getRegistrationId(String phone) {
        String rid = JPushInterface.getRegistrationID(getActivity());
        if (rid.isEmpty()) {
            ToastUtils.s(getActivity(),"Get registration fail, JPush init failed!");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void refreshList(UpdateUserInfoEvent updateUserInfoEvent) {
        getInfo();
        getIncomeInfo();
        fresh_message();
    }

    /**
     * 刷新未读消息
     */
    public void fresh_message(){
        if(checkLogin()){
            RequestManager
                    .mRetrofitManager
                    .createRequest(RetrofitRequestInterface.class)
                    .getUnReadMessage()
                    .enqueue(new RetrofitCallBack() {
                        @Override
                        public void onSuccess(String response) {
                            Logger.i("mine---red---"+ response);
                            JSONObject jsonObject = JSON.parseObject(response);
                            String rCode = jsonObject.getString("code");
                            String rMsg  = jsonObject.getString("msg");
                            if("1000".equals(rCode)) {
                                init(jsonObject);
                            }else{
                                Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                            }
                        }
                        @Override
                        public void onError(Throwable t) {
                            Logger.i(t.getMessage());
                            Toast.makeText(getActivity(),"获取未读消息失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
    public String getStringValue(JSONObject json, String key){
        String ret = "";
        try{
            ret = json.getString(key);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    //初始界面未读标识
    public void init(JSONObject jsonObject){
        if(jsonObject!=null) {
            JSONArray jarr = jsonObject.getJSONArray("data");
            int msgCount = 0;
            int productCount = 0;
            for (int i = 0; i < jarr.size(); i++) {
                JSONObject jsono = (JSONObject) jarr.get(i);
                String msgType = getStringValue(jsono, "messageType");
                try {
                    if ("01".equals(msgType) || "03".equals(msgType))
                        msgCount = msgCount + Integer.valueOf(getStringValue(jsono, "unreadCount"));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(msgCount > 0){
                tvMsgFlag.setVisibility(View.VISIBLE);
            }else{
                tvMsgFlag.setVisibility(View.GONE);
            }

        }else{
            tvMsgFlag.setVisibility(View.GONE);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private PopupWindow mPopupWindow;

    private void showPopupWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_call_phone, null);
            TextView takePhotoTV = view.findViewById(R.id.tv_pop_pictrue_select_take);
            TextView cancelTV = view.findViewById(R.id.tv_pop_pictrue_select_cancel);
            takePhotoTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + "400-180-8199");
                    intent.setData(data);
                    startActivity(intent);
                }
            });
            cancelTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                }
            });
            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        }

    }



}
